const express = require('express');
const fs = require('fs');
const path = require('path');

const data = require('./data.json');

const dbpath = path.join(__dirname, 'data.json');
// json 写入
// 添加学生
exports.add = function (body, callback) {
  body.id = data.students.length + 1;
  data.students.push(body);
  fs.writeFile(dbpath, JSON.stringify(data), err => {
    if (err) {
      callback(err);
    }
    callback(null);
  });
};

// 修改学生
exports.edit = function (body, callback) {
  body.id = parseInt(body.id);
  var Data = data.students.find(item => item.id === parseInt(body.id));
  for (var k in body) {
    Data[k] = body[k];
  }
  fs.writeFile('./data.json', JSON.stringify(data), err => {
    if (err) {
      callback(err);
    }
    callback(null);
  });
};

//删除学生
exports.delete = function (ID, callback) {
  let index = data.students.findIndex(item => item.id === parseInt(ID.id))
    data.students.splice(index, 1)
    fs.writeFile(dbpath,JSON.stringify(data),(err) => {
      if(err){
        callback(err)
      }
      callback(null)
    })
}

exports.find = function(err,res) {
  if(err) {
    return status(500).send('Server err')
  }
  res.redirect('/')
}
